<template>
  <el-drawer
    v-model="drawer"
    :title="contractType === '1' ? '新增销售合同' : '新增采购合同'"
    :with-header="true"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="项目编号：">
        <el-input v-model="ruleForm.projectNumber" disabled />
      </el-form-item>
      <el-form-item label="合同编号：" prop="contractNumber">
        <el-input v-model="ruleForm.contractNumber" placeholder="请输入合同编号" />
      </el-form-item>
      <el-form-item label="合同名称：" prop="contractName">
        <el-input v-model="ruleForm.contractName" placeholder="请输入合同名称" />
      </el-form-item>
      <el-form-item label="客户名称：" prop="clientId" v-if="contractType === '1'">
        <el-select
          v-model="ruleForm.clientId"
          filterable
          placeholder="请选择客户"
          style="width: 100%"
        >
          <el-option
            v-for="ite in clientList"
            :key="ite.id"
            :label="ite.clientName"
            :value="ite.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商名称：" prop="supplierId" v-if="contractType === '0'">
        <el-autocomplete
          v-model="ruleForm.supplierName"
          :fetch-suggestions="querySearch"
          :trigger-on-focus="true"
          clearable
          class="inline-input w-50"
          placeholder="请输入供应商名称"
          style="width: 100%"
          maxlength="64"
        />
      </el-form-item>
      <el-form-item label="合同金额：" prop="contractAmount">
        <el-input-number
          v-model="ruleForm.contractAmount"
          placeholder="请输入合同金额"
          style="width: 220px"
          :precision="2"
          :min="0"
        />
        &nbsp;&nbsp;元
      </el-form-item>
      <el-form-item label="签订时间：" prop="contractDate">
        <el-date-picker
          v-model="ruleForm.contractDate"
          type="date"
          placeholder="请选择签订时间"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          style="width: 320px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { postMarketingContract } from '@/api/controller/marketing-contract-controller/index'
  import { postProcurementContract } from '@/api/controller/procurement-contract-controller/index'
  import { postClientMatch } from '@/api/controller/client-controller/index'
  import { postSupplierMatch } from '@/api/controller/supplier-controller/index'
  import { validator } from '@/utils/numberFormat.ts'
  const drawer = ref(false)
  const contractType = ref('1')
  const clientList = ref([])
  const show = async (val, type) => {
    contractType.value = type
    let res
    if (type === '1') {
      res = await postClientMatch({})
      clientList.value = res.data
    } else if (type === '0') {
      restaurants.value = []
      res = await postSupplierMatch({})
      for (let i = 0; i < res.data.length; i++) {
        restaurants.value.push({ value: res.data[i].supplierName })
      }
    }

    ruleForm.value = {
      projectNumber: val,
      contractNumber: null,
      contractName: null,
      contractDate: null,
      clientId: null,
      contractAmount: null,
      supplierName: '',
    }
    drawer.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref({
    projectNumber: null,
    contractNumber: null,
    contractName: null,
    contractDate: null,
    clientId: null,
    contractAmount: null,
    supplierName: '',
  })

  const rules = reactive({
    contractNumber: [
      { required: true, message: '请输入合同编号', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    contractName: [
      { required: true, message: '请输入合同名称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    clientId: [{ required: true, message: '请选择客户', trigger: 'blur' }],
    supplierName: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
    contractDate: [{ required: true, message: '请输入签订日期', trigger: 'blur' }],
    contractAmount: [
      { required: true, message: '请输入合同金额', trigger: 'blur' },
      { validator, trigger: 'blur' },
    ],
  })
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        let result
        if (contractType.value === '1') {
          result = await postMarketingContract(ruleForm.value, { loading: true })
        } else {
          result = await postProcurementContract(ruleForm.value, { loading: true })
        }
        if (result.code === 200) {
          ElMessage.success('添加成功')
          emit('getData')
          drawer.value = false
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const restaurants = ref([])
  const querySearch = (queryString: string, cb: any) => {
    const results = queryString
      ? restaurants.value.filter((item) => item.value.indexOf(queryString) >= 0)
      : restaurants.value
    // call callback function to return suggestions
    cb(results)
  }
  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>

<style scoped lang="scss"></style>
